'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'


export default function SimpleLoginPage() {
  const [formData, setFormData] = useState({
    account: '',
    password: ''
  })
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  
  const router = useRouter()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError('')

    try {
      if (!/^[A-Za-z][A-Za-z0-9]*$/.test(formData.account.trim())) {
        setError('')
      }
      // 调用登录API
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          username: formData.account,
          password: formData.password,
        }),
      })

      const result = await response.json()

      if (!result.success) {
        setError(result.error || '登录失败，请检查用户名和密码')
        return
      }

      // 登录成功，跳转到dashboard（middleware会自动添加时间戳）
      router.push('/dashboard')
    } catch (err) {
      console.error('登录错误:', err)
      setError('登录失败，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4 bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      <div className="w-full max-w-md">
        <div className="bg-white/20 backdrop-blur-lg border border-white/30 rounded-3xl shadow-xl p-8">
          <div className="text-center mb-8">
            <div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-gradient-to-r from-blue-500 to-purple-600 flex items-center justify-center">
              <span className="text-white text-2xl font-bold">奥</span>
            </div>
            <h1 className="text-2xl font-bold text-gray-800">欢迎回来</h1>
            <p className="text-gray-600 mt-2">登录您的奥数学院账户</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            {error && (
              <div className="p-3 rounded-lg bg-red-100 border border-red-300 text-red-700 text-sm">
                {error}
              </div>
            )}

            <div>
              <label htmlFor="account" className="block text-sm font-medium text-gray-700 mb-2">
                用户名
              </label>
              <input
                id="account"
                name="account"
                type="text"
                required
                placeholder="请输入用户名（字母或字母+数字）"
                value={formData.account}
                onChange={handleInputChange}
                className="w-full px-4 py-3 rounded-xl bg-white/15 backdrop-blur-sm border border-white/25 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-300"
              />
            </div>

            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
                密码
              </label>
              <input
                id="password"
                name="password"
                type="password"
                required
                placeholder="请输入密码"
                value={formData.password}
                onChange={handleInputChange}
                className="w-full px-4 py-3 rounded-xl bg-white/15 backdrop-blur-sm border border-white/25 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-300"
              />
            </div>

            <button
              type="submit"
              disabled={isLoading}
              className="w-full py-3 px-4 bg-gradient-to-r from-blue-500 to-purple-600 text-white font-semibold rounded-xl hover:from-blue-600 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300"
            >
              {isLoading ? '登录中...' : '登录'}
            </button>
          </form>

          <div className="mt-6 text-center">
            <p className="text-sm text-gray-600">
              还没有账户？{' '}
              <a href="/auth/register" className="font-medium text-blue-600 hover:text-blue-500">
                立即注册
              </a>
            </p>
          </div>

          <div className="mt-4 p-3 rounded-lg bg-blue-50 border border-blue-200">
            <p className="text-xs text-blue-700 text-center">
              <strong>演示账户：</strong><br/>
              学生：用户名 demo_student / 密码 demo123<br/>
              管理员：用户名 admin / 密码 admin@123
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
